// pages/me/bindIdCard/bindIdCard.js
import { Api } from "../../../utils/api.js"
import { Http } from '../../../utils/http.js'
import { config } from '../../../config.js'
let http = new Http()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    idCard_0: '',
    idCard_1: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 自定义方法
   */
  chooseImage: function (e) {
    var that = this
    var type = e.currentTarget.dataset.type
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '正在上传',
          mask: true
        })
        const tempFilePaths = res.tempFilePaths
        that.uploadImage(tempFilePaths[0], function(key) {
          let imageName = `idCard_${type}`
          that.setData({
            [imageName]: config.image_url + key
          })
          wx.hideLoading()
          wx.showToast({
            title: '上传成功',
          })
        })
      }
    })
  },

  uploadImage: function (image, callback) {
    http.sendHttp(Api.get_upload_token, {
      data: {},
      success: function (res) {
        wx.uploadFile({
          url: config.qiniu_upload_host,
          filePath: image,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data"
          },
          formData: {
            token: res.data.obj.token,
          },
          success: function (res) {
            var data = JSON.parse(res.data)
            callback(data.key)
          },
          fail: function (res) {
            wx.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            })
          }
        })
      }
    })
  },

  bindIdCard: function () {
    var idCard_0 = this.data.idCard_0
    var idCard_1 = this.data.idCard_1
    if (idCard_0.length > 0 && idCard_1.length > 0) {
      http.sendHttp(Api.bind_user_idcard, {
        data: {
          idCardFace: idCard_0,
          idCardBack: idCard_1
        },
        success: function (res) {
          wx.showToast({
            title: '上传成功',
          })
          setTimeout(function() {
            wx.navigateBack({})
          }, 1000)
        }
      }, 'POST')
    } else {
      wx.showToast({
        title: '请上传身份证照片',
        icon: 'none'
      })
    }
  }
})